<template>
  <div class="azm-poster-canvas maxWidth500 azm-fixed-top" @mousewheel="handleMousewheel">
    <div class="azm-scroll">
      <mu-paper :zDepth="20" id="posterCanvasContainer"
                :style="{height: `${posterHeight}px`,width:`${scaleWidth}%`}">
        <div class="posterModel clearfix" v-if="editShow">
          <vue-svg-draggable-resizable :scaling="scale"></vue-svg-draggable-resizable>
        </div>
        <vue-poster-svg :model="model"></vue-poster-svg>
      </mu-paper>
    </div>
    <footer>
      <van-stepper class="azm-stepper clearfix" v-model="scale" integer :min="10" :max="100" :step="2"></van-stepper>
    </footer>
  </div>
</template>

<script>
  import device from '../../libs/device'
  import { Stepper } from 'vant'
  import RichTextEditor from '../../components/richTextEditor'
  import Deploy2style from '../../libs/deploy2style'
  import { Paper } from 'muse-ui'
  import { mapState } from 'vuex'
  import config from '../../libs/config'
  import VueDraggableResizable from 'vue-draggable-resizable'
  import VueSvgDraggableResizable from '../../components/vue-svg-draggable-resizable/svg-canvas'

  import VuePosterSvg from '../../components/vue-poster-svg'
  import io from 'socket.io-client'

  const PROXY_URL = `${config.host}/nodeapi/proxy_image?url=`
  const TEXT_SCALE = 0.89

  let ScaleTimer = null
  let ScrollTimer = null

  let defaultScale = 90
  let defaultHeightStatus = true

  export default {
    components: {
      [VuePosterSvg.name]: VuePosterSvg,
      [Paper.name]: Paper,
      [Stepper.name]: Stepper,
      [RichTextEditor.name]: RichTextEditor,
      'vue-draggable-resizable': VueDraggableResizable,
      'vue-svg-draggable-resizable': VueSvgDraggableResizable
    },
    watch: {
      scale (n, o) {
        let that = this
        that.handleResize()
      }
    },
    data () {
      return {
        editShow: false,
        socket: null,
        socketStatus: false,
        message: '',
        isHH: false,
        options: {
          vuescroll: {
            mode: 'slide',
            scroller: {
              bouncing: true,
              locking: true
            },
            zooming: false
          },
          scrollPanel: {
            scrollingY: true,
            scrollingX: false,
            speed: 800,
          },
          bar: {
            keepShow: false,
            opacity: 0,
            background: 'rgb(3, 185, 118)',
            showDelay: 500
          },
          rail: {
            keepShow: false,
            opacity: 0,
            background: '#01a99a',
          }
        },
        model: {
          'image': 'http://app.mmtcapp.com/static/upload/image/20181101/20181101142548_13480.png',
          'title': '美容',
          'w': 750,
          'h': 1200,
          'background': 'http://app.mmtcapp.com/static/upload/image/20181101/20181101142553_64410.png'
        },
        configList: [
          {
            'id': '1418',
            'type': '0',
            'content': 'A delicate woman, at least, knows how to please herself',
            'image': '',
            'status': '1',
            'vertical_align': 'center',
            'basic': {
              'x': '0px',
              'y': '1011px',
              'w': '750px',
              'h': '18px',
              'z_index': '1',
              'color': '#ffffff',
              'font_size': '17px',
              'line_height': '40px',
              'text_align': 'center'
            },
            'customize': {
              'rotate': '0',
              'opacity': '1',
              'text-decoration': '',
              'font-weight': '',
              'font-style': '',
              'letter-spacing': '1px'
            }
          },
          {
            'id': '1415',
            'type': '3',
            'content': '美   丽                 是   一  种    充   满\n活力的艺术',
            'image': '',
            'status': '1',
            'vertical_align': 'middle',
            'basic': {
              'x': '134px',
              'y': '132px',
              'w': '300px',
              'h': '100px',
              'z_index': '1',
              'color': '#ffffff',
              'font_size': '31px',
              'line_height': '40px',
              'text_align': 'left'
            },
            'customize': {
              'rotate': '0',
              'opacity': '1',
              'text-decoration': '',
              'font-weight': '',
              'font-style': '',
              'letter-spacing': '1px'
            }
          },
          {
            'id': '1416',
            'type': '0',
            'content': '2018',
            'image': '',
            'status': '1',
            'vertical_align': 'center',
            'basic': {
              'x': '580px',
              'y': '187px',
              'w': '67px',
              'h': '21px',
              'z_index': '1',
              'color': '#ffffff',
              'font_size': '25px',
              'line_height': '40px',
              'text_align': 'left'
            }
          },
          {
            'id': '1417',
            'type': '0',
            'content': '一个  精  致 的  女人，   最起                                 码懂    得取悦自己',
            'image': '',
            'status': '1',
            'vertical_align': 'center',
            'basic': {
              'x': '0px',
              'y': '977px',
              'w': '750px',
              'h': '28px',
              'z_index': '1',
              'color': '#ffffff',
              'font_size': '29px',
              'line_height': '40px',
              'text_align': 'center'
            },
            'customize': {
              'rotate': '0',
              'opacity': '1',
              'text-decoration': '',
              'font-weight': '',
              'font-style': '',
              'letter-spacing': '2px'
            }
          },
          {
            'id': '1414',
            'type': '1',
            'content': 'http://app.mmtcapp.com/static/upload/image/20181101/20181101142740_99230.jpg',
            'image': 'http://app.mmtcapp.com/static/upload/image/20181101/20181101142740_99230.jpg',
            'status': '1',
            'vertical_align': '',
            'basic': {
              'x': '120px',
              'y': '251px',
              'w': '510px',
              'h': '690px',
              'z_index': '1',
              'color': '',
              'font_size': '',
              'line_height': '',
              'text_align': 'center'
            },
            'customize': {
              'rotate': '0',
              'opacity': '1',
              'background-color': '',
              'border-width': '1px',
              'border-color': '',
              'border-style': '',
              'border-radius': '0px'
            }
          },
          {
            'id': '1413',
            'type': '2',
            'content': 'https://app.mmtcapp.com/nodeapi/qrcode/shop_home?id=8662',
            'image': 'http://app.mmtcapp.com/static/upload/image/20181101/20181101142701_80521.jpg',
            'status': '1',
            'vertical_align': '',
            'basic': {
              'x': '317px',
              'y': '1059px',
              'w': '116px',
              'h': '116px',
              'z_index': '1',
              'color': '',
              'font_size': '',
              'line_height': '',
              'text_align': 'center'
            },
            'customize': {
              'rotate': '0',
              'opacity': '1',
              'background-color': '',
              'border-width': '1px',
              'border-color': '',
              'border-style': '',
              'border-radius': '0px'
            },
            'tip': '替换此店铺二维码?',
            'tip2': '用户扫码即可进入您的店铺小程序'
          }
        ],
        posterList: [],
        placeholderPic: 1,
        posterWidth: 300,
        scaleWidth: this.scale,
        posterHeight: 456,
        maxPosterHeight: 667,
        scrollBoxHeight: 667,
        scale: defaultScale,
        isLocking: true,
        draggableGroup: null,
        keyboard: {
          height: 312,
          status: 0
        },
        draggableObj: {
          width: 0.1,
          height: 0.1,
          top: 0.1,
          left: 0.1,
          bbox: {},
          rbox: {},
          transform: {},
          id: '',
          node: null
        }
      }
    },
    computed: {
      ...mapState({})
    },
    inject: ['appRefresh', 'isMerchantH5'],
    beforeCreate () {
      this.socket && this.socket.close()
    },
    created () {
      let $ = this.util.Zepto
      let that = this
      let obj = {}
      if (config.NODE_ENV === 'production') {
        obj.path = '/nodeapi/socket.io'
      }
      let socket = that.socket = io(`${config.host}/wsFonts`, obj)
      // 加入房间
      socket.on('connect', function () {
        that.$toast.message('socket连接成功')
        that.SVG_JS()
      })
      if (device.mobile()) {
        $(document).focusin(function () {
          let keyboard = that.keyboard
          //软键盘弹出的事件处理
          // alert('软键盘弹出的事件处理')
          that.keyboard.status > 0 && $(window).scrollTop(that.keyboard.top || 0)
          $(document).on('scroll', function () {
            if (that.keyboard.status > 0) {
              $(window).scrollTop(that.keyboard.top || 0)
            } else {
              clearTimeout(ScrollTimer)
              ScrollTimer = setTimeout(function () {
                if (keyboard.status === 0) {
                  that.keyboard.height = $(this).scrollTop()
                }
                that.keyboard.status++
                $(window).scrollTop(that.keyboard.top || 0)
                document.title = `高度：${that.keyboard.height},次数：${that.keyboard.status}`
              }, 300)
            }
          })
        })
        $(document).focusout(function () {
          //软键盘收起的事件处理
          alert('软键盘收起的事件处理')
        })
      }
      this.$nextTick(async function () {

      })
      $(window).resize(function () {
        that.handleResize(true)
        if (!that.$device.isAndroid) {
          window.setTimeout(function () {
            window.scrollTo(0, document.body.clientHeight)
          }, 500)
        }
      })
    },
    destroyed () {
      this.socket && this.socket.close()
    },
    methods: {
      async SVG_JS () {
        let that = this
        let $ = that.util.Zepto
        let scale = that.scale
        let model = that.model
        let dom = $(that.$el)
        let canvas = dom.find('#posterCanvasContainer')
        let scrollBox = dom.find('.azm-scroll')
        await that.handleResize(true)
        that.scrollBoxHeight = scrollBox.height()
        
        let configList = that.configList

        function compare (property) {
          return function (a, b) {
            let value1 = 0
            let value2 = 0
            try {
              value1 = eval('a.' + property)
              value2 = eval('b.' + property)
            } catch (err) {
            }
            return value1 - value2
          }
        }

        // 元素排序
        configList.sort(compare('basic.z_index'))

        let arr = []
        for (let item of configList) {
          let style = {...Deploy2style.basisFilter(item.basic), ...Deploy2style.basisFilter(item.customize)}
          for (let k in style) {
            let val = style[k]
            if (Deploy2style.isPixel(val) || /^-?\d{0,}.?\d+$/ig.test(val)) {
              style[k] = parseFloat(val)
            }
          }
          console.log(style, '++++++++++++++++ss++++++++++++++')
          setTimeout(function () {
            if ('0, 3'.indexOf(item.type) > -1) {//文字

            } else if ('1'.indexOf(item.type) > -1) {//图片

            } else if ('2'.indexOf(item.type) > -1) {//二维码

            }
          })
        }
      },
      // 鼠标滚轮事件
      handleMousewheel (e) {
        let that = this
        // console.log(e, '鼠标滚轮事件');
        if (e.deltaY > 0) {
          this.scale -= 1
        } else {
          this.scale += 1
        }
        // setTimeout(function () {
        //   that.handleResize(true)
        // }, 300)
      },
      handleResize (bol) {
        // this.$toast.message(9090);
        let that = this
        const $ = this.util.Zepto
        const dom = $(this.$el)
        dom.height($(window).height())
        const container = dom.find('#posterCanvasContainer')
        const azmScrollBox = dom.find('.azm-scroll')
        const model = this.model
        if (!model.h || !model.w) {
          return
        }
        const aspectRatio = model.w / model.h
        let scaleWidth = this.scale
        if (scaleWidth < 10 || scaleWidth > 100) {
          scaleWidth = scaleWidth < 10 ? 10 : 100
        }
        let posterWidth = 0
        let azmScrollWidth = azmScrollBox.width() * (scaleWidth / 100)
        let azmScrollHeight = azmScrollBox.height() * 0.9
        that.maxPosterHeight = azmScrollHeight
        // console.log(azmScrollWidth, azmScrollHeight, '父盒子');
        let posterHeight = azmScrollWidth / aspectRatio
        // console.log(posterHeight, bol, 'svg盒子高度');
        if (posterHeight > azmScrollHeight && bol === true) {
          posterWidth = azmScrollHeight * aspectRatio
          defaultScale = scaleWidth = Math.round(posterWidth / azmScrollBox.width() * 100)
          // if (defaultScale < 70) {
          //   scaleWidth = 70
          // }
        } else {
          posterWidth = azmScrollWidth
        }
        // console.log(scaleWidth, posterWidth, posterHeight, '百分比:宽：高');
        this.scaleWidth = scaleWidth
        this.posterHeight = posterHeight
        this.posterWidth = posterWidth
        this.scale = scaleWidth
      },
      handleScroll (e) {
        // console.log(e);
        // if (defaultHeightStatus) {
        //   defaultHeightStatus = false;
        //   this.posterHeight++;
        // } else {
        //   defaultHeightStatus = true;
        //   this.posterHeight--;
        // }
      }
    }
  }
</script>

<style scoped lang="less">
  * {
    box-sizing: border-box;
  }

  .azm-poster-canvas {
    height: 100%;
    width: 100%;
    position: relative;
    margin: 0 auto;
    display: flex;
    flex-direction: column;

    .posterModel2 {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 100%;
      height: 100%;
      background: transparent;
      z-index: 1000;
    }

    .posterModel {
      position: fixed;
      /*top: 50%;*/
      /*left: 50%;*/
      /*transform: translate(-50%, -50%);*/
      /*width: 100%;*/
      /*height: 100%;*/
      background: transparent;
      z-index: 1000;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;

      .azm-poster-draggable {
        position: absolute;
        top: 0;
        left: 0;
        width: 0;
        height: 0;
        border: 1px solid #fff;
      }
    }

    #posterCanvasContainer {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .azm-scroll {
      position: relative;
      flex: 1;
      touch-action: auto;
      overflow: hidden;
    }

    footer {
      box-sizing: border-box;
      padding: 10px 0;
      height: 45px;
      line-height: 45px;
      text-align: center;
      background-color: #fff;
      vertical-align: middle;
    }

    #posterCanvasContainer, .posterCanvasContainer {
      width: 80%;
      margin: 0 auto;
      background-color: transparent;
      text-align: center;
    }

    @media screen and (min-width: 500px) {
      #posterCanvasContainer, .posterCanvasContainer {
        width: 100%;
      }
    }
    /*.posterCanvasContainer {*/
    /*position: absolute;*/
    /*top: 0;*/
    /*left: 0;*/
    /*z-index: 100;*/
    /*background-color: rgba(0, 0, 0, .3);*/
    /*}*/
  }


</style>
<style lang="less">
  html.html-poster_svg {
    position: fixed;
    /*z-index: 10000000;*/
    user-select: none;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;

    body, #app {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
  }

  .azm-poster-canvas {
    /*.__vuescroll {*/
    /*.__panel.__slide {*/
    /*padding: 10px 0;*/
    /*}*/
    /*}*/

    .hoveMove {
      cursor: move;
    }

    svg:not(:root), symbol, image, marker, pattern, foreignObject {
      overflow: hidden;
    }

    footer {

    }
  }
</style>
